/*
    Project:        Home Power Control
    File:           HPCMCP3008.h
    Author:         christian@karunamusic.at
    Date:           02.2015
    Description:    Class to access and query the A/D converter-chip MCP3008 via SPI.
 */

#ifndef HPCMCP3008_H
#define HPCMCP3008_H

#include <QObject>
#include <QString>

/** \brief Class to access and query the A/D converter-chip MCP3008 via SPI.
 */
class HPCMCP3008 : public QObject
{
    Q_OBJECT
public:
    /** \brief Constructor with default values.
     *
     *  The defaults are:
     *    devspi = "/dev/spidev0.0"
     *    spiMode = SPI_MODE_0;
     *    spiSpeed = 1000000;
     *    spiBitsPerWord = 8;
     */
    explicit HPCMCP3008();

    /** \brief Constructor with given SPI values.
     *
     * \param devspi SPI device file (usually /dev/spidev0.0 (or .1)
     * \param spiMode defines the SPI Mode used.
     * \param spiSpeed Bus speed or SPI clock frequency.
     * \param spiBitPerWord defines the bit width of the data transmitted.
     */
    explicit HPCMCP3008( const QString& devspi, unsigned char spiMode, unsigned int spiSpeed, unsigned char spiBitsPerWord );

    /** \brief Destructor.
     */
    virtual ~HPCMCP3008();

    /** \brief Write/Read to/from the MCP3008.
     *
     * \param data pointer to the data-array
     * \param length data length
     * \return number of bytes transmitted
     *
     * This method writes data "data" of length "lenght" to the MCP.
     * Data shifted from the MCP is saved back into "data".
     */
    int spiWriteRead( unsigned char *data, int length );

private:
    unsigned char m_Mode; /**< SPI Mode */
    unsigned char m_BitsPerWord; /**< SPI Bits/Word */
    unsigned int m_Speed; /**< SPI bus speed */
    int m_spifd; /**< file handle */

    /** \brief Opens the SPI device.
     *
     * \param devspi SPI device file (usually /dev/spidev0.0 (or .1)
     * \return status value.
     *
     * It is responsible for opening the spidev device "devspi"
     * and then setting up the spidev interface.
     * Private member variables are used to configure spidev.
     * They must be set appropriately by constructor before calling
     * this function!
     */
    int spiOpen( const QString& devspi );

    /** \brief Closes the SPI device.
     *
     * \return status value.
     */
    int spiClose();
};

#endif // HPCMCP3008_H
